package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eduplatform.common.JwtUtils;
import com.eduplatform.dto.QuestionDTO;
import com.eduplatform.entity.Question;
import com.eduplatform.entity.Subject;
import com.eduplatform.entity.User;
import com.eduplatform.mapper.QuestionMapper;
import com.eduplatform.mapper.SubjectMapper;
import com.eduplatform.mapper.UserMapper;
import com.eduplatform.service.QuestionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 试题Service实现类
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<QuestionDTO> pageQuestions(int page, int size, Integer type, Integer difficulty,
            Long subjectId, Integer educationLevel, String keyword) {
        Page<Question> questionPage = new Page<>(page, size);

        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (type != null) {
            wrapper.eq(Question::getType, type);
        }

        if (difficulty != null) {
            wrapper.eq(Question::getDifficulty, difficulty);
        }

        if (subjectId != null) {
            wrapper.eq(Question::getSubjectId, subjectId);
        }

        if (educationLevel != null) {
            wrapper.eq(Question::getEducationLevel, educationLevel);
        }

        if (StringUtils.hasText(keyword)) {
            wrapper.like(Question::getContent, keyword);
        }

        // 按创建时间降序排序
        wrapper.orderByDesc(Question::getCreateTime);

        // 执行分页查询
        IPage<Question> result = page(questionPage, wrapper);

        // 转换为DTO对象
        IPage<QuestionDTO> dtoPage = result.convert(this::convertToDTO);

        // 批量查询学科和创建人信息
        if (!dtoPage.getRecords().isEmpty()) {
            // 获取所有学科ID和创建人ID
            List<Long> subjectIds = dtoPage.getRecords().stream()
                    .map(QuestionDTO::getSubjectId)
                    .distinct()
                    .collect(Collectors.toList());

            List<Long> creatorIds = dtoPage.getRecords().stream()
                    .map(QuestionDTO::getCreatorId)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量查询学科信息
            List<Subject> subjects = subjectMapper.selectBatchIds(subjectIds);
            Map<Long, String> subjectMap = subjects.stream()
                    .collect(Collectors.toMap(Subject::getId, Subject::getName));

            // 批量查询创建人信息
            List<User> users = userMapper.selectBatchIds(creatorIds);
            Map<Long, String> userMap = users.stream()
                    .collect(Collectors.toMap(User::getId, User::getUsername));

            // 设置学科名称和创建人姓名
            for (QuestionDTO dto : dtoPage.getRecords()) {
                dto.setSubjectName(subjectMap.getOrDefault(dto.getSubjectId(), ""));
                dto.setCreatorName(userMap.getOrDefault(dto.getCreatorId(), ""));
            }
        }

        return dtoPage;
    }

    @Override
    public QuestionDTO getQuestionDetail(Long id) {
        Question question = getById(id);
        if (question == null) {
            return null;
        }

        QuestionDTO dto = convertToDTO(question);

        // 查询学科信息
        Subject subject = subjectMapper.selectById(question.getSubjectId());
        if (subject != null) {
            dto.setSubjectName(subject.getName());
        }

        // 查询创建人信息
        User user = userMapper.selectById(question.getCreatorId());
        if (user != null) {
            dto.setCreatorName(user.getUsername());
        }

        return dto;
    }

    @Override
    @Transactional
    public boolean addQuestion(QuestionDTO questionDTO) {

        Question question = new Question();
        BeanUtils.copyProperties(questionDTO, question);

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        question.setCreateTime(now);
        question.setUpdateTime(now);

        // 确保creatorId不为空
        if (question.getCreatorId() == null) {
            throw new IllegalArgumentException("创建人ID不能为空");
        }

        return save(question);
    }

    @Override
    @Transactional
    public boolean updateQuestion(QuestionDTO questionDTO) {
        Question question = getById(questionDTO.getId());
        if (question == null) {
            return false;
        }

        BeanUtils.copyProperties(questionDTO, question);

        // 更新时间
        question.setUpdateTime(LocalDateTime.now());

        return updateById(question);
    }

    @Override
    @Transactional
    public boolean deleteQuestion(Long id) {
        return removeById(id);
    }

    /**
     * 将实体对象转换为DTO对象
     */
    private QuestionDTO convertToDTO(Question question) {
        QuestionDTO dto = new QuestionDTO();
        BeanUtils.copyProperties(question, dto);
        return dto;
    }
}